import Taro from "@tarojs/taro";
import {WXUserinfo} from "@/utils/model";
import LocalData from "@/common/local_data";
import NumberUtils from "@/utils/number_utils";
import Utils from "@/utils/common";

class LocalUtils {
  static getLocalStorage(key: string) {
    const str = Taro.getStorageSync(key)
    if (!str) {
      return []
    }
    return JSON.parse(str)
  }

  static getLocalStorageArray(key: string): any[] { // 明确返回类型
    const str = Taro.getStorageSync(key)
    if (!str) {
      return []
    }
    try { // 增加 try-catch 保证健壮性
      const parsed = JSON.parse(str);
      return Array.isArray(parsed) ? parsed : [];
    } catch (e) {
      return [];
    }
  }


  //set
  static setLocalStorage(key: string, value: any) {
    let str = value;
    if (typeof value !== 'string') {
      str = JSON.stringify(value)
    }
    Taro.setStorageSync(key, str)
  }

  static getLocalStr(key: string) {
    return Taro.getStorageSync(key);
  }

  //set
  static setLocalStr(key: string, value: any) {
    Taro.setStorageSync(key, value)
  }

  static removeLocalStorage(key: string) {
    Taro.removeStorageSync(key)
  }

  static getUserinfo(): WXUserinfo {
    const username = LocalUtils.getLocalStr(LocalData.nickname)
    const avatar = LocalUtils.getLocalStr(LocalData.avatarUrl)
    const idNo = LocalUtils.getLocalStr(LocalData.idNo)
    const mobile = LocalUtils.getLocalStr(LocalData.mobile)
    const realName = LocalUtils.getLocalStr(LocalData.realName)
    const company = LocalUtils.getLocalStr(LocalData.company)
    return {
      mobile, realName, idNo, username, avatar, company
    }
  }

  //获取手机号和真实姓名
  static getMobileOrRealName() {
    const mobile = LocalUtils.getLocalStr(LocalData.mobile)
    const realName = LocalUtils.getLocalStr(LocalData.realName)
    return {mobile, realName}
  }

  static setUserinfo(nickname, avatarUrl, mobile, authentication, realName = null, idNo = null, company = null) {
    if (realName) {
      LocalUtils.setLocalStr(LocalData.realName, realName)
    }
    if (idNo) {
      LocalUtils.setLocalStr(LocalData.idNo, idNo)
    }
    if (company) {
      LocalUtils.setLocalStr(LocalData.company, company)
    }
    this.setIdCard(authentication)
    this.setUserinfo2(nickname, avatarUrl, mobile);
  }

  static setUserinfo2(nickname, avatarUrl, mobile) {
    if (nickname) {
      LocalUtils.setLocalStr(LocalData.nickname, nickname)
    }
    if (avatarUrl) {
      LocalUtils.setLocalStr(LocalData.avatarUrl, avatarUrl)
    }
    this.setMobile(mobile)
  }

  static setIdCard(authentication) {
    if (authentication) {
      LocalUtils.setLocalStr(LocalData.authentication, `${authentication}`)
    }
  }

  static setMobile(mobile) {
    if (mobile) {
      LocalUtils.setLocalStr(LocalData.mobile, mobile)
    }
  }

  static setUserId(userId) {
    if (userId) {
      LocalUtils.setLocalStr(LocalData.userId, userId)
    }
  }

  static getUserId() {
    return LocalUtils.getLocalStr(LocalData.userId)
  }

  static isVIdCard() {
    const idCard = LocalUtils.getLocalStr(LocalData.authentication)
    return NumberUtils.stringToNumber(idCard) > 0;
  }

  static getMobile(): boolean {
    const mobile = LocalUtils.getLocalStr(LocalData.mobile)
    return mobile && mobile.length === 11;
  }

  static getToken(): string {
    return LocalUtils.getLocalStr(LocalData.token);
  }

  static setToken(token: string) {
    LocalUtils.setLocalStr(LocalData.token, token);
  }


  static exitLogin() {
    LocalUtils.removeLocalStorage(LocalData.token);
    LocalUtils.removeLocalStorage(LocalData.authentication);
    LocalUtils.removeLocalStorage(LocalData.mobile);
  }

  //判断是否登录
  static isLogin(): boolean {
    const token = LocalUtils.getToken();
    return Utils.isNotBlank(token);
  }


  static getHistoryList(): string[] {
    // 直接复用 getLocalStorage，它已经处理了空情况和JSON解析
    return this.getLocalStorageArray(LocalData.HISTORY_STORAGE_KEY);
  }


  static addHistoryItem(newItem: string, limit: number = 10) {
    // 1. 校验输入项是否为空或仅有空格
    if (!newItem || !newItem.trim()) {
      return;
    }
    const trimmedItem = newItem.trim();

    // 2. 获取当前的历史记录
    const currentList = this.getHistoryList();

    // 3. 过滤掉已存在的相同项，实现去重和更新位置
    const filteredList = currentList.filter(item => item !== trimmedItem);

    // 4. 将新项添加到数组的最前面
    const newList = [trimmedItem, ...filteredList];

    // 5. 根据限制裁剪数组
    const limitedList = newList.slice(0, limit);

    // 6. 将更新后的列表存回本地
    this.setLocalStorage(LocalData.HISTORY_STORAGE_KEY, limitedList);
  }

  static clearHistoryList() {
    this.removeLocalStorage(LocalData.HISTORY_STORAGE_KEY);
  }


}

export default LocalUtils
